package com.changgou.goods.controller;

import com.changgou.entity.PageResult;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.goods.pojo.Category;
import com.changgou.goods.pojo.Spec;
import com.changgou.goods.service.CategoryService;
import com.changgou.goods.service.SpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/spec")
public class SpecController {
    @Autowired
    private SpecService specService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 模板查询
     * @return
     */
    @GetMapping(value = "/selectFormwork")
    public Result selectFormwork(){
         List<String> specList = specService.selectAll();
        if (specList.size()>0) {
            return new Result(true, StatusCode.ERROR,"模板拉取失败");
        }
         return new Result(true, StatusCode.OK,"模板拉取成功",specList);

    }

    /**
     * 商品添加
     * @param category
     * @return
     */
    @GetMapping(value = "/addClassify")
    public Result addClassify(@RequestBody Category category){
        categoryService.add(category);
        return new Result(true,StatusCode.OK,"商品添加成功");
    }

    /**
     * 根据id删除规格
     * @param id
     * @return
     * zxq
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        try {
            specService.deleteById(id);
            return new Result(true,StatusCode.OK,"删除规格成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"删除规格失败");
        }
    }
    @PostMapping
    public Result add(@RequestBody Spec spec){
        try {
            specService.add(spec);
            return new Result(true,StatusCode.OK,"添加规格成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加规格失败");
        }
    }

    /**
     * 查询规格列表数据
     * @param id
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/{id}/{page}/{size}")
    public Result findById(@PathVariable int id , @PathVariable  int page, @PathVariable  int size){
        try {
            PageResult<Spec> pageResult = specService.findPageById(id, page, size);
            return new Result(true,StatusCode.OK,"查询成功",pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
    }

    /***
     * 跟据分类id查询规格模板集合
     * @param categoryId
     * @return
     */
    @GetMapping("/category/{id}")
    public Result<List<Spec>> findCategoryById(@PathVariable(value = "id") Integer categoryId){
        List<Spec> specList = specService.findByCategory(categoryId);
        return new Result(true,StatusCode.OK,"查询规格参数成功",specList);
    }
 }
